package com.apicloud.modulerecordscreen;

import android.content.Context;

import com.uzmap.pkg.uzkit.request.APICloudHttpClient;
import com.uzmap.pkg.uzkit.request.HttpGet;
import com.uzmap.pkg.uzkit.request.HttpResult;
import com.uzmap.pkg.uzkit.request.RequestCallback;

import org.json.JSONObject;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class S94Token {
    private static final int CODE_INIT = 2;
    public static String message = ""; //错误提示消息
    private static int code = CODE_INIT; //0拒绝，1允许，2未知
    private static boolean runing = false;

    private static String packageName = null;
    private static String key = null;


    private static void verify(){
        if(key==null || key.indexOf(".") == -1 ) {
            code = 0;
            return;
        }
        String[] arr = key.split("\\.",2);
        String param = "package="+packageName+"&module="+S94Token.class.getPackage().getName()+"&key="+arr[0];
        //MD5加密
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            return;
        }
        md5.update(param.getBytes());
        String token  = new BigInteger(1, md5.digest()).toString(16);
        //小于32位，添加前置0
        for (int i = 0; i < 32 - token.length(); i++) {
            token = "0" + token;
        }
        String url = "http://s94.top/home/other/verify_apicloud_token?"+param+"&token="+token+"&id="+arr[1];
        HttpGet get = new HttpGet(url);
        get.addCallback(new RequestCallback() {
            public void onFinish(final HttpResult result) {
                runing = false;
                if(result.success()){
                    try {
                        JSONObject res = new JSONObject(result.data);
                        code = res.getInt("code");
                        message = res.getString("msg");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        runing = true;
        APICloudHttpClient.instance().request(get);
    }
    public static boolean isPass(Context context, String _key){
        String _packageName = context.getPackageName();
        if(!_packageName.equals(packageName) || !_key.equals(key)){
            packageName = _packageName;
            key = _key;
            code = CODE_INIT;
        }
        if(code==0) return false;
        if(code!=1 && !runing) verify();
        return true;
    }
    public static boolean isPass(){
        if(code==0) return false;
        if(code!=1 && !runing) verify();
        return true;
    }
}
